<template>
  <el-dialog :visible="showRoleDialog" title="分配角色" @close="btnClose">
    <!-- 表单 -->
    <el-form>
      <el-form-item>
        <el-checkbox-group v-model="roleIds">
          <el-checkbox v-for="item in list" :key="item.id" :label="item.id">
            {{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-row type="flex" justify="center">
        <el-col :span="9">
          <el-button @click="btnClose">取消</el-button>
          <el-button type="primary" @click="btnOk">确定</el-button>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script>
// 按钮
// 保存
import { getAllRoleAPI, getUserDetailByIdAPI, assignRolesAPI } from '@/api'
export default {
  name: 'AssignRole',
  props: {
    // 弹层显示
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 哪个用户的角色
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      list: [], // 所有用户的角色
      roleIds: [''] // 当前用户的角色
    }
  },
  created() {
    this.getAllRole()
  },
  methods: {
    async getAllRole() {
      const { rows } = await getAllRoleAPI({
        page: 1,
        pagesize: 20 // 任意 角色不会很多 就20条
      })
      this.list = rows
    },
    async getUserDetailInfo(id) {
      try {
        const { roleIds } = await getUserDetailByIdAPI(id)
        if (roleIds === null) {
          this.roleIds = []
          return
        }
        this.roleIds = roleIds
        console.log(roleIds)
        // 打印出来确实是没有数据
      } catch (error) {
        this.$message(error)
      }
    },
    async btnOk() {
      try {
        const res = await assignRolesAPI({
          id: this.userId,
          roleIds: this.roleIds
        })
        console.log(res)
        this.$message.success('分配权限成功')
        this.$emit('update:showRoleDialog', false)
      } catch (err) {
        this.$message.error('分配权限失败')
      }
    },
    btnClose() {
      this.roleIds = [] // 清空弹层 不要上次的数据
      // 关闭弹层
      this.$emit('update:showRoleDialog', false)
    }
  }
}
</script>

<style>

</style>
